package com.xgimi.open.skill.datamanager.web.component;

import com.alibaba.fastjson.JSON;
import com.xgimi.commons.base.Result;
import com.xgimi.open.skill.datamanager.biz.common.exception.BizException;
import com.xgimi.open.skill.datamanager.biz.common.exception.ParamException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;

/**
 * @author coderzpw.zhang
 * @version 1.0
 * @description 全局异常捕获
 * @date 2023/2/3 15:06
 */
@ControllerAdvice
@Slf4j
@Order(1)
public class GlobalExceptionHandler {

    /**
     * json参数 - 后端用对象接收
     *
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleCustomException(HttpServletResponse response, MethodArgumentNotValidException exception) {
        log.error("参数异常：{}", JSON.toJSONString(exception.getBindingResult().getAllErrors()));
        Result result = buildErrorResult(response, 400, exception.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return result;
    }

    @ResponseBody
    @ExceptionHandler(ParamException.class)
    public Result handleCustomException(HttpServletResponse response, ParamException exception) {
        log.error("参数异常：{}", JSON.toJSONString(exception.getMessage()));
        Result result = buildErrorResult(response, 400, exception.getMessage());
        return result;
    }

    @ResponseBody
    @ExceptionHandler(BizException.class)
    public Result handleCustomException(HttpServletResponse response, BizException bizException) {
        log.error("业务异常：{}", JSON.toJSONString(bizException.getMessage()));
        Result result = buildErrorResult(response, bizException.getCode(), bizException.getMessage());
        return result;
    }

    private Result buildErrorResult(HttpServletResponse response, Integer code, String message) {
        response.setContentType("application/json;charset=UTF-8");
        return genErrorResult(code, message);
    }

    private Result genErrorResult(Integer errorCode, String message) {
        Result dto = new Result();
        dto.setCode(errorCode);
        dto.setMessage(message);
        dto.setData(Collections.EMPTY_MAP);
        return dto;
    }
}
